/**
 *  关于谷歌字体的信息操作
 */

export type FontMetaData = {
    /** 这个不是 fontFamily */
    fontId: string;
    /** 这个才是真的 fontFamily */
    fontName: string;
    /** 语言标签，一般第一项为语言 */
    subsets: string[];
    /** 字重清单 */
    weights: number[];
    /** 样式清单 */
    styles: string[];
    defSubset: string;
    variable: boolean;
    lastModified: string;
    version: string;
    category: string;
    source: string;
    license: string;
    type: string;
};

export const FontList: string[] = [];
/* 获取所有字体的列表 */
export const getFontList = async () => {
    if (FontList.length) return FontList;
    const datalist = await fetch("https://api.fontsource.org/fontlist", {
        cache: "force-cache",
    }).then((res) => res.json());
    const list = Object.entries(datalist)
        .filter(([_, key]) => {
            return key === "google";
        })
        .map((i) => i[0]);
    FontList.push(...list);
    return list;
};

/** 获取 css 文件的 URL */
export const getCSSURL = (
    name: string,
    fontWeight = "index",
    root = "https://cdn.jsdelivr.net/npm/@fontsource/"
) => {
    return `${root}${name}/${fontWeight}.css`;
};

/** 用于存放 metadata 的响应式空间 */
export const fontData = new Map<string, FontMetaData>();

/** 获取 Google 字体对应的 MetaData  */
export const getMetaData = (name: string) => {
    if (fontData.has(name)) {
        return fontData.get(name);
    }
    return fetch(
        `https://cdn.jsdelivr.net/npm/@fontsource/${name}/metadata.json`,
        {
            cache: "force-cache",
        }
    )
        .then((res) => res.json())
        .then((data) => {
            fontData.set(name, data);
            return data;
        });
};

export const useGoogleFontData = () => {
    return {
        fontData,
        getFontList,
        getCSSURL,
        getMetaData,
        async getFontByName(name: string) {
            const meta = await getMetaData(name);
            return { meta, css: getCSSURL(name) };
        },
    };
};
